
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports _2bMatesSite.BO

Namespace _2bMatesSite
	''' <summary>
	''' Summary description for view_news.
	''' </summary>
	Public Partial Class view_news
		Inherits BaseWebPage
		Protected newsInterview As BO.ArticleItem
		Protected usr As User
		Protected col As Integer = DirectCast(ArticleItem.ArticleItemType.ritNews, Integer)
		Protected id As Integer = -1
		Protected pageID As Integer = -1
		Protected lblPageTitle As System.Web.UI.WebControls.Label
		'protected System.Web.UI.WebControls.Label lblUserName;

		Protected htPageConstants As New Hashtable()
		Protected period As DateTime = DateTime.Now

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
			' Put user code to initialize the page here
			' this.pageTemplate.PageTitle = PageTitles.VIEW_NEWS_PAGE;
			usr = LoggedUser

			If usr = Nothing Then
				Common.Utils.RedirectToLoginPage(Page)
			End If

			Me.RegisterStartupScript("resizeImages", Constants.RESIZE_NEWS_IMAGE_SCRIPT)
			Me.pageTemplate.onLoadScript = "resizeImages()"

			Me.initPageTitles(Constants.VIEW_NEWS, "", Form1, Nothing, htPageConstants)
			Me.initAdvertisements(Form1, Nothing)

			' init tabs
			ucMusicTabs.PageName = Constants.VIEW_NEWS

			If Request.Params("id") = Nothing OrElse Request.Params("id") = "" Then
				Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
			End If

			If Request.Params(Constants.SPECIAL_PAGE_TYPE_ID_PARAM) = Nothing OrElse Request.Params(Constants.SPECIAL_PAGE_TYPE_ID_PARAM) = "" Then
				Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
			End If

			If Request.Params("col") = Nothing OrElse Request.Params("col") = "" Then
				Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
			End If

			If Constants.SHOW_MUSIC <> Constants.SHOW_ON Then
				Throw New Exception(Constants.ERROR_MESSAGE_NO_ACCESS)
			End If

			Try
				id = Convert.ToInt32(Request.Params("id"))

				pageID = Convert.ToInt32(Request.Params(Constants.SPECIAL_PAGE_TYPE_ID_PARAM))

				col = Convert.ToInt32(Request.Params("col"))

				If col <> DirectCast(ArticleItem.ArticleItemType.ritInterview, Integer) AndAlso col <> DirectCast(ArticleItem.ArticleItemType.ritNews, Integer) Then
					Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
				End If
			Catch
				Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
			End Try

			newsInterview = ArticleItem.GetArticleItemByID(id)

			Dim CurrentPage As SpecialPage = SpecialPages.GetSpecialPageByID(pageID)

			If CurrentPage = Nothing Then
				Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
			End If

			lblTitle.Text = HttpUtility.HtmlEncode(newsInterview.Title)
			'Server.HtmlDecode(newsInterview.Title);
			lblSubtitle.Text = HttpUtility.HtmlEncode(newsInterview.Subtitle)
			'Server.HtmlDecode(newsInterview.Subtitle);
			lblNews.Text = Server.HtmlDecode(newsInterview.Content)

			litPageLabel.Text = CurrentPage.Name
			If newsInterview.Type = ArticleItem.ArticleItemType.ritInterview Then
				ucMusicTabs.ActiveTab = 2
			Else
				ucMusicTabs.ActiveTab = 1
				lblLCTitle.Text = GetPageConstText(htPageConstants, "CONST_LCTitle_TEXT")
				lblRCTitle.Text = GetPageConstText(htPageConstants, "CONST_RCTitle_TEXT")
			End If

			imgNewsImage.Attributes.Add("name", Constants.NEWS_IMAGES_NAME)
			If newsInterview.Img <> Nothing Then
				imgNewsImage.ImageUrl = Pictures.GetPictureSrcFullURL(-1, newsInterview.ID, Constants.IMAGE_IS_NEWS, "", "../")
			Else
				imgNewsImage.Visible = False
			End If

			Dim isPicVisible As Boolean = False

			If newsInterview.UserID > 0 Then
				Dim pic As UserPicture = Users.GetUserByID(newsInterview.UserID).DefaultPicture
				If (newsInterview.Img = Nothing) AndAlso (pic <> Nothing) Then
					hlUserGroup.ImageUrl = Pictures.GetPictureSrcFullURL(pic, True, "../")
					isPicVisible = True
				End If

				Dim itemUser As User = Users.GetUserByID(newsInterview.UserID)
				'lblUserName.Text = HttpUtility.HtmlEncode(itemUser.Name);	
				hlUserGroup.Text = HttpUtility.HtmlEncode(itemUser.Name)
				hlUserGroup.NavigateUrl = "../" + Constants.MEMBERS + "?id=" + itemUser.ID
ElseIf newsInterview.GroupID > 0 Then
				Dim pic As GroupPicture = Groups.GetGroupByID(newsInterview.GroupID).DefaultPicture
				If (newsInterview.Img = Nothing) AndAlso (pic <> Nothing) Then
					hlUserGroup.ImageUrl = Pictures.GetPictureSrcFullURL(pic, True, "../")
					isPicVisible = True
				End If

				Dim itemGroup As Group = Groups.GetGroupByID(newsInterview.GroupID)
				'lblUserName.Text = HttpUtility.HtmlEncode(itemGroup.Name);
				hlUserGroup.Text = HttpUtility.HtmlEncode(itemGroup.Name)
				hlUserGroup.NavigateUrl = "../" + Constants.GROUP + "?" + Constants.GROUP_PARAM + "=" + itemGroup.ID
			End If


			hlUserGroup.Visible = isPicVisible
			txtComment.Attributes.Add("onKeyDown", Constants.ON_KEY_DOWN_SCRIPT.Replace(Constants.TEXT_AREA_MAX_CHARS_TAG, Constants.TEXT_AREA_MESSAGES_MAX_CHARS.ToString()))
			txtComment.Attributes.Add("onKeyUp", Constants.ON_KEY_UP_SCRIPT.Replace(Constants.TEXT_AREA_MAX_CHARS_TAG, Constants.TEXT_AREA_MESSAGES_MAX_CHARS.ToString()))

			period = Common.DateUtilities.GetStartOfQuarter(newsInterview.ArticleDate.Year, Common.DateUtilities.GetQuarter(DirectCast(newsInterview.ArticleDate.Month, Common.Month)))
			' Bind data
			If Not IsPostBack Then
				BindGrid()
				BindLeftGrid()
			End If
		End Sub

		Protected Function CreateDataSource() As ICollection
			Dim commentsList As ArrayList = newsInterview.Comments()
			Dim dt As New DataTable()
			Dim startIndex As Integer = 0
			Dim endIndex As Integer = -1
			Dim LoggedUsersList As ArrayList = Common.Utils.GetLoggedUsersIDs()

			endIndex = startIndex + commentsList.Count

			dt.Columns.Add(New DataColumn("SenderID", GetType(Integer)))
			dt.Columns.Add(New DataColumn("SenderName", GetType(String)))
			dt.Columns.Add(New DataColumn("SenderImageURL", GetType(String)))
			dt.Columns.Add(New DataColumn("OnlineImg", GetType(String)))
			dt.Columns.Add(New DataColumn("MemberURL", GetType(String)))
			dt.Columns.Add(New DataColumn("Date", GetType(String)))
			dt.Columns.Add(New DataColumn("Time", GetType(String)))
			dt.Columns.Add(New DataColumn("Comment", GetType(String)))
			dt.Columns.Add(New DataColumn("CommentID", GetType(String)))
			dt.Columns.Add(New DataColumn("ButtonsVisibility", GetType(Boolean)))
			dt.Columns.Add(New DataColumn("OnClickJS", GetType(String)))
			dt.Columns.Add(New DataColumn("SenderNameFull", GetType(String)))

			If commentsList.Count = 0 Then
				dgComments.Visible = False
				lblNoComments.Visible = True
			Else
				Dim curCommentDate As DateTime
				Dim dr As DataRow
				Dim temp As UserPicture
				Dim curSender As User
				Dim riComment As ArticleItem.ArticleItemComment

				' List user's inbox messages
				Dim i As Integer = startIndex
				While i < endIndex
					dr = dt.NewRow()

					endIndex = Math.Min(endIndex, commentsList.Count)
					dr = dt.NewRow()
					riComment = DirectCast(commentsList(i), ArticleItem.ArticleItemComment)
					curCommentDate = riComment.[Date]
					curSender = Users.GetUserByID(riComment.PostedByUserID)

					dr(0) = riComment.PostedByUserID
					dr(1) = getBeginning(HttpUtility.HtmlEncode(curSender.Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)
					temp = curSender.DefaultPicture
					If temp <> Nothing Then
						dr(2) = Pictures.GetPictureSrcFullURL(temp, True, "../")
					Else
						dr(2) = Constants.DEFAULT_THUMBNAIL_IMAGE_URL
					End If
					If LoggedUsersList.Contains(curSender.ID) Then
						dr(3) = "../images/online_status.gif"
					Else
						dr(3) = "../images/spacer.gif"
					End If

					dr(4) = Users.ComposeMemeberLink(curSender)
					dr(10) = Users.ComposeMemeberLinkOnClickJS(curSender, trUserCanceledMessage)

					dr(5) = curCommentDate.DayOfWeek + ", " + Constants.MONTHS(curCommentDate.Month - 1) + " " + curCommentDate.Day + ", " + curCommentDate.Year
					dr(6) = curCommentDate.ToShortTimeString()
					dr(7) = showLinksInMessage(riComment.Comment, False)
					dr(8) = riComment.ID
					If LoggedUser.Status = Constants.appAdmin Then
						dr(9) = True
					Else
						dr(9) = False
					End If

					dr(11) = curSender.Name

					dt.Rows.Add(dr)
					System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
				End While
			End If
			Dim dv As New DataView(dt)
			Return dv
		End Function

		Protected Sub BindGrid()
			dgComments.DataSource = CreateDataSource()
			dgComments.DataBind()
		End Sub

		Protected Function CreateLeftDataSource() As ICollection
			Dim contentItems As ArrayList

			If col = DirectCast(ArticleItem.ArticleItemType.ritInterview, Integer) Then
				contentItems = SpecialPage.GetArticleItems(pageID, Convert.ToInt32(ArticleItem.ArticleItemType.ritInterview), period, -1, -1, -1)
			Else
				contentItems = SpecialPage.GetArticleItems(pageID, Convert.ToInt32(ArticleItem.ArticleItemType.ritNews), period, -1, -1, -1)
				'contentItems = SpecialPage.GetArticleItems(pageID, Convert.ToInt32(ArticleItem.ArticleItemType.ritInterview), DateTime.Now, Constants.MUSIC_ITEM_LC_MAX, this.newsInterview.UserID, this.newsInterview.GroupID);
				'contentItems = SpecialPage.GetArticleItems(pageID, Convert.ToInt32(ArticleItem.ArticleItemType.ritNews), DateTime.Now, Constants.MUSIC_ITEM_LC_MAX, this.newsInterview.UserID, this.newsInterview.GroupID);
			End If

			Dim dt As New DataTable()

			Dim contentItemsCount As Integer = contentItems.Count
			dgNewsItems.AllowSorting = True

			If contentItemsCount <= 0 Then
				lblNoNewsItems.Visible = True
				dgNewsItems.Visible = False
			Else
				Dim dr As DataRow
				dt.Columns.Add(New DataColumn("MemberName", GetType(String)))
				dt.Columns.Add(New DataColumn("ItemID", GetType(Integer)))
				dt.Columns.Add(New DataColumn("ItemURL", GetType(String)))
				dt.Columns.Add(New DataColumn("ItemName", GetType(String)))

				' List left items
				Dim user As User = Nothing
				Dim grp As Group = Nothing

				For Each result As ArticleItem In contentItems
					dr = dt.NewRow()

					If result.UserID > 0 Then
						user = BO.Users.GetUserByID(result.UserID)
						dr(0) = Me.getBeginning(HttpUtility.HtmlEncode(user.Name), Constants.MAX_NAME_LENGTH_ABOVE_MUSIC_TRACKS)
ElseIf result.GroupID > 0 Then
						grp = BO.Groups.GetGroupByID(result.GroupID)
						dr(0) = Me.getBeginning(HttpUtility.HtmlEncode(grp.Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)
					End If
					dr(1) = result.ID
					dr(2) = "../" + Constants.VIEW_NEWS + "?" + Constants.SPECIAL_PAGE_TYPE_ID_PARAM + "=" + pageID + "&id=" + result.ID + "&col=" + DirectCast(result.Type, Integer)
					dr(3) = result.Title
					dt.Rows.Add(dr)
				Next
			End If

			Dim dv As New DataView(dt)
			Return dv
		End Function

		Protected Sub BindLeftGrid()
			'init datagrid with database data ordered by "orederBy" param
			dgNewsItems.DataSource = CreateLeftDataSource()
			dgNewsItems.DataBind()
		End Sub


		#region Web Form Designer generated code
		Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
			'
			' CODEGEN: This call is required by the ASP.NET Web Form Designer.
			'			
			InitializeComponent()
			MyBase.OnInit(e)
		End Sub

		''' <summary>
		''' Required method for Designer support - do not modify
		''' the contents of this method with the code editor.
		''' </summary>
		Private Sub InitializeComponent()
			AddHandler Me.dgComments.ItemCommand, AddressOf Me.dgComments_ItemCommand

		End Sub
#End Region

		Protected Sub btnPostComment_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			If Page.IsValid Then
				Dim comment As String = ""

				comment = Server.HtmlDecode(txtComment.Text.Trim())
				comment = comment.Substring(0, Math.Min(comment.Length, Constants.TEXT_AREA_MESSAGES_MAX_CHARS))

				trItem.Visible = False
				trConfirmItem.Visible = True
				litPageLabel.Text = GetPageConstText(htPageConstants, "CONST_ConfirmPageTitle_TEXT")
				'"Confirm my comment";
				lblComment.Text = comment
			End If
		End Sub

		Protected Sub btnPost_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Dim comment As String = lblComment.Text
			Dim niComment As ArticleItem.ArticleItemComment = Nothing

			niComment = New ArticleItem.ArticleItemComment(id, usr.ID, comment)
			niComment.Save()
			Response.Redirect(Constants.VIEW_NEWS + "?id=" + id + "&" + Constants.SPECIAL_PAGE_TYPE_ID_PARAM + "=" + pageID + "&col=" + col)
		End Sub

		Protected Sub btnEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			trItem.Visible = True
			trConfirmItem.Visible = False
		End Sub

		Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.VIEW_NEWS + "?id=" + id + "&" + Constants.SPECIAL_PAGE_TYPE_ID_PARAM + "=" + pageID + "&col=" + col)
		End Sub

		Private Sub dgComments_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
			Dim lbPushed As LinkButton = DirectCast(e.CommandSource, LinkButton)
			Dim cmd As String = e.CommandName
			If cmd = "Delete" Then
				Dim riComment As ArticleItem.ArticleItemComment = ArticleItem.GetCommentByID(Convert.ToInt32(e.CommandArgument))
				If riComment <> Nothing Then
					riComment.DoDelete()
					BindGrid()
				End If
			End If
		End Sub

	End Class
End Namespace






